package com.sendpo.zjx.sendpo.fragment;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.Adapter;
import android.support.v7.widget.RecyclerView.OnScrollListener;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import ch.ielse.view.imagewatcher.ImageWatcher;
import com.bumptech.glide.BitmapRequestBuilder;
import com.bumptech.glide.BitmapTypeRequest;
import com.bumptech.glide.DrawableTypeRequest;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.gongwen.marqueen.MarqueeFactory;
import com.google.gson.Gson;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.jingchen.pulltorefresh.PullableRecyclerView;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.activity.LoginActivity;
import com.sendpo.zjx.sendpo.activity.MainActivity;
import com.sendpo.zjx.sendpo.activity.SendpoPindanListActivity;
import com.sendpo.zjx.sendpo.activity.StoreMainAllProduceActivity;
import com.sendpo.zjx.sendpo.activity.UserActiveInfoActvitiy;
import com.sendpo.zjx.sendpo.domain.FriendCircleDomain;
import com.sendpo.zjx.sendpo.domain.FriendCircleDomain.DataBean;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;
import de.hdodenhof.circleimageview.CircleImageView;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.xutils.common.Callback;
import org.xutils.common.Callback.CancelledException;
import org.xutils.common.Callback.CommonCallback;
import org.xutils.common.util.DensityUtil;

/**
 * Created by zjx on 2018
 */

@SuppressLint("ValidFragment")
public class YanchuFragment_Saishi extends BaseMainFragment {
    private int currentlastitem = 0;
    private boolean lastloading = false;
    private int pagenow = 1;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    View rootView;
    @BindView(value = R.id.pulltofresh)
   public PullToRefreshLayout pulltofresh;

   private RecylcerAdaper adpter;
   public LinearLayoutManager lm;
   public int position=0;
    @SuppressLint("ValidFragment")
    public YanchuFragment_Saishi(int position){
        this.position=position;
    }
    public View initView()
    {
        View localView = View.inflate(this.mActivity, R.layout.fragment_yanchusaishi_layout, null);
        ButterKnife.bind(localView, this.mActivity);
        return localView;
    }

    public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle)
    {
        if (rootView == null)
        {
            this.rootView = super.onCreateView(paramLayoutInflater, paramViewGroup, paramBundle);
            ButterKnife.bind(this, this.rootView);
            initData();
        }
        return this.rootView;
    }

    private void initData() {
        lm=new LinearLayoutManager(mActivity, OrientationHelper.VERTICAL,false);
        pulltofresh.setPullUpEnable(false);
        pulltofresh.setOnPullListener(new PullToRefreshLayout.OnPullListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                List localList = Xutils.queryAll(mActivity.getApplication(), User.class);
                if ((localList == null) || (localList.size() == 0))
                {
                    query(pagenow, 0,mActivity.userCity,mActivity.userArea, mActivity.userLongitude + "", mActivity.userLatitude + "", mActivity.userAddress, position+"");
                    return;
                }
                query(pagenow, ((User)localList.get(0)).getUserId().intValue(), mActivity.userCity, mActivity.userArea, mActivity.userLongitude + "", mActivity.userLatitude + "", mActivity.userAddress, position+"");
            }
            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {

            }
        });
        List<FriendCircleDomain.DataBean> dataBeans=new ArrayList<>();
        recyclerview.setLayoutManager(lm);
        recyclerview.setAdapter(new RecylcerAdaper(mActivity,dataBeans));
        pulltofresh.autoRefresh();
    }

    public class RecylcerAdaper extends  RecyclerView.Adapter<RecyclerView.ViewHolder>{
        public List<FriendCircleDomain.DataBean> dataBeen;
        public LayoutInflater inflater;
        public RecylcerAdaper(Context context, List<FriendCircleDomain.DataBean> dataBeen)
        {
            this.inflater = LayoutInflater.from(context);
            this.dataBeen = dataBeen;
        }
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new IndexHoler(this.inflater.inflate(R.layout.layout_yanchusaishi_listitem, parent, false));
        }


        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
               final IndexHoler ih= (IndexHoler) holder;
            final FriendCircleDomain.DataBean dataBean = (FriendCircleDomain.DataBean)this.dataBeen.get(position);
            Glide.with(mActivity)
                    .load(dataBean.getUseravatar())
                    .asBitmap()
                    .animate(R.anim.fade_in)
                    .centerCrop()
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                            ih.head_icon.setImageBitmap(resource);
                        }
                    });
            ih.head_icon.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View view)
                {
                    Map<String,Object>map = new HashMap();
                    map.put("id", Integer.valueOf(dataBean.getUserId()));
                    Tools.redirectActivity(YanchuFragment_Saishi.this.mActivity, StoreMainAllProduceActivity.class, map);
                }
            });
            ih.title.setText("" + dataBean.getUserFriendscircleTag());
            ih.content.setText("" + dataBean.getUserFriendscircleText());
            ih.watchnum.setText("" + dataBean.getUserFriendscircleLooknumber());
            ih.location.setText("" + dataBean.getUserArea());
            ih.all_ll.removeAllViews();
            List<String> imgs = dataBean.getImgs();
            if (imgs != null && imgs.size() != 0) {
                final List<String> ivs_s = new ArrayList<>();
                final List<ImageView> ivs = new ArrayList<>();
                for (String img : imgs) {
                    final ImageView iv = new ImageView(mActivity);
                    iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(DensityUtil.dip2px(158), DensityUtil.dip2px(158));
                    lp.setMargins(0, 0, DensityUtil.dip2px(10), 0);
                    iv.setLayoutParams(lp);
                    iv.setBackgroundColor(getResources().getColor(R.color.default_lightgray));
                    Glide.with(mActivity)
                            .load(img)
                            .asBitmap()
                            .animate(R.anim.fade_in)
                            .placeholder(getResources().getColor(R.color.default_lightgray))
                            .override(500, 500)
                            .into(iv);
                    iv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            mActivity.vImageWatcher.show(iv, ivs, ivs_s);
                        }
                    });
                    ivs.add(iv);
                    ivs_s.add(img);
                    ih.all_ll.addView(iv);
                }
            }


            if (dataBean.isUserFriendscircleState()) {
                ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon_focus);

            } else {
                ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon);

            }

            ih.goods_bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    List<User> userList = Xutils.queryAll(mActivity.getApplication(), User.class);

                    if (userList == null || userList.size() == 0) {
                        Tools.redirectActivity(mActivity, LoginActivity.class);
                        return;
                    }

                    if (dataBean.isUserFriendscircleState()) {
                        ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon);
                        dataBean.setUserFriendscircleState(false);
                        int count = Integer.parseInt(ih.goood_tv.getText().toString().trim() + "");
                        count--;
                        ih.goood_tv.setText(count + "");
                        nofocus(userList.get(0).getUserId() + "", dataBean.getUserFriendscircleId() + "");
                    } else {
                        ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon_focus);
                        dataBean.setUserFriendscircleState(true);
                        int count = Integer.parseInt(ih.goood_tv.getText().toString().trim() + "");
                        count++;
                        ih.goood_tv.setText(count + "");
                        focus(userList.get(0).getUserId() + "", dataBean.getUserFriendscircleId() + "");
                    }
                }
            });
            ih.goood_tv.setText("" + dataBean.getDynamicPraiseCount());
            System.out.println("*********************"+dataBean.getGuestcount());
            ih.guest_tv.setText("" + dataBean.getGuestcount());
            ih.tag_ll.removeAllViews();
            String officialTag = dataBean.getUserFriendscircleOfficialTag();
            if (TextUtils.isEmpty(officialTag)) {
                return;
            }
            ih.guest_tv.setText("" + dataBean.getGuestcount());
            ih.guest_bt.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View paramAnonymousView)
                {
                   Map<String,Object> map = new HashMap();
                    map.put("data", dataBean);
                    Tools.redirectActivity(YanchuFragment_Saishi.this.mActivity, UserActiveInfoActvitiy.class, map);
                }
            });
            ih.watch_bt.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View paramAnonymousView)
                {
                    Map<String,Object> map = new HashMap();
                    map.put("data", dataBean);
                    Tools.redirectActivity(YanchuFragment_Saishi.this.mActivity, UserActiveInfoActvitiy.class, map);
                }
            });
            ih.rootView.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View paramAnonymousView)
                {
                    Map<String,Object> map = new HashMap();
                    map.put("data", dataBean);
                    Tools.redirectActivity(YanchuFragment_Saishi.this.mActivity, UserActiveInfoActvitiy.class, map);
                }
            });
            ih.all_ll.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View paramAnonymousView)
                {
                    Map<String,Object> map = new HashMap();
                    map.put("data", dataBeen);
                    Tools.redirectActivity(YanchuFragment_Saishi.this.mActivity, UserActiveInfoActvitiy.class, map);
                }
            });
            ih.address.setText("" + dataBean.getUserAddress());
           String[]  strings =officialTag.split(",");
            if (strings==null||strings.length==0) {
                return;
            }
             for(int i=0;i<strings.length;i++){
                String str=strings[i];
                 TextView textView = new TextView(mActivity);
                 textView.setText("" + str);
                 LinearLayout.LayoutParams  lp = new LinearLayout.LayoutParams(DensityUtil.dip2px(35.0F), DensityUtil.dip2px(20.0F));
                 lp.setMargins(DensityUtil.dip2px(5.0F), DensityUtil.dip2px(5.0F), DensityUtil.dip2px(5.0F), DensityUtil.dip2px(5.0F));
                 textView.setLayoutParams(lp);
                 textView.setTextSize(8.0F);
                 textView .setGravity(17);
                 textView.setTextColor(getResources().getColor(R.color.white));
                 if(str.equals("100人")){
                     textView.setBackgroundColor(getResources().getColor(R.color.default_yellow1));
                 }else if(str.equals("300人")){
                     textView.setBackgroundColor(getResources().getColor(R.color.default_yellow1));
                 }else if(str.equals("500人")){
                     textView.setBackgroundColor(getResources().getColor(R.color.default_yellow1));
                 }else if(str.equals("1000人")){
                     textView.setBackgroundColor(getResources().getColor(R.color.default_yellow1));
                 }else if(str.equals("一起狂欢")){
                     textView.setBackgroundColor(getResources().getColor(R.color.default_blue));
                 }else if(str.equals("靓女靓仔")){
                     textView.setBackgroundColor(getResources().getColor(R.color.default_theme));
                 }else if(str.equals("机会难得")){
                     textView.setBackgroundColor(getResources().getColor(R.color.default_theme));
                 }else if(str.equals("一起哈皮")){
                     textView.setBackgroundColor(getResources().getColor(R.color.default_theme));
                 } else if(str.equals("免费")){
                     textView.setBackgroundColor(getResources().getColor(R.color.default_blue));
                 }else if(str.equals("收费")){
                     textView.setBackgroundColor(getResources().getColor(R.color.default_blue));
                 }
                 ih.tag_ll.addView(textView);
             }
        }

        @Override
        public int getItemCount() {
            return dataBeen.size();
        }
        public void focus(String userId, String userFriendscircleId) {
            HashMap localHashMap = new HashMap();
            localHashMap.put("userId", "" + userId);
            localHashMap.put("userFriendscircleId", userFriendscircleId);
            Xutils.POST(HttpUrl.friendcirclepraiseAdd, localHashMap, new CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

        }
        public void nofocus(String userId, String userFriendscircleId) {
            HashMap localHashMap = new HashMap();
            localHashMap.put("userId", "" + userId);
            localHashMap.put("userFriendscircleId", userFriendscircleId);
            Xutils.POST(HttpUrl.friendcirclepraiseDelete, localHashMap, new CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

        }
        public void delete(int position) {
            this.dataBeen.remove(position);
            notifyDataSetChanged();
        }
        public void initAppend(List<FriendCircleDomain.DataBean> paramList) {
            this.dataBeen.addAll(paramList);
            notifyDataSetChanged();
        }

        public void initRefresh(List<FriendCircleDomain.DataBean> paramList) {
            this.dataBeen.removeAll(this.dataBeen);
            this.dataBeen.addAll(paramList);
            notifyDataSetChanged();
        }

        public class IndexHoler extends RecyclerView.ViewHolder {
            public TextView address;
            public LinearLayout all_ll;
            public TextView content;
            public RelativeLayout goods_bt;
            public ImageView goods_iv;
            public TextView goood_tv;
            public RelativeLayout guest_bt;
            public TextView guest_tv;
            public CircleImageView head_icon;
            public TextView location;
            public View rootView;
            public LinearLayout tag_ll;
            public TextView title;
            public RelativeLayout watch_bt;
            public TextView watchnum;
            public IndexHoler(View rootView) {
                super(rootView);
                this.address = rootView.findViewById(R.id.address);
                this.rootView = rootView;
                this.head_icon = rootView.findViewById(R.id.head_icon);
                this.title = rootView.findViewById(R.id.title);
                this.all_ll =  rootView.findViewById(R.id.all_ll);
                this.watchnum = rootView.findViewById(R.id.watchnum);
                this.goods_iv = rootView.findViewById(R.id.goods_iv);
                this.goods_bt = rootView.findViewById(R.id.goods_bt);
                this.goood_tv =  rootView.findViewById(R.id.goood_tv);
                this.guest_bt = rootView.findViewById(R.id.guest_bt);
                this.watch_bt = rootView.findViewById(R.id.watch_bt);
                this.guest_tv =rootView.findViewById(R.id.guest_tv);
                this.content=rootView.findViewById(R.id.content);
                this.location =rootView.findViewById(R.id.location);
                this.tag_ll = rootView.findViewById(R.id.tag_ll);
            }
        }

    }


      public void query(final int pagenow, final int userId, final String userCity,
                        final String userArea, final String userLongitude, final String userLatitude, final String userAddress, final String userFriendscircleType){
         Map<String,String> map = new HashMap();
          map.put("pagenow", pagenow + "");
          map.put("userId", userId + "");
          map.put("userCity", "" + userCity);
          map.put("userArea", "" + userArea);
          map.put("userLongitude", "" + userLongitude);
          map.put("userLatitude", "" + userLatitude);
          map.put("userAddress", "" + userAddress);
          map.put("userFriendscircleType", "" + userFriendscircleType);
          System.out.println("************************usefriendcircleBylocationresult:*"+pagenow+"userId"+userId+"userCity"+userCity
          +userArea+"userArea");
          Xutils.POST(HttpUrl.usefriendcircleBylocation, map, new CommonCallback<String>() {
              @Override
              public void onSuccess(String result) {
            pulltofresh.refreshFinish(PullToRefreshLayout.SUCCEED);
                  Gson gson=new Gson();
                  FriendCircleDomain domain=gson.fromJson(result,FriendCircleDomain.class);
                  if (domain.getData() != null && domain.getData().size() != 0) {
                      if (adpter == null) {
                          recyclerview.setAdapter(adpter = new RecylcerAdaper(mActivity,domain.getData()));
                          recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
                              @Override
                              public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                  super.onScrollStateChanged(recyclerView, newState);
                                  if (currentlastitem == lm.getItemCount() - 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                                      if (YanchuFragment_Saishi.this.pagenow == 1 && adpter.dataBeen.size() >= 10 && lastloading == false) {
                                          YanchuFragment_Saishi.this.pagenow++;
                                          append(pagenow,userId,userCity,userArea,userLongitude,
                                                  userLatitude,userAddress,userFriendscircleType);
                                      }
                                  }
                              }

                              @Override
                              public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                  super.onScrolled(recyclerView, dx, dy);
                                  currentlastitem = lm.findLastVisibleItemPosition();
                              }
                          });
                      } else {
                          adpter.initRefresh(domain.getData());
                      }

                  }
              }

              @Override
              public void onError(Throwable ex, boolean isOnCallback) {
                  pulltofresh.refreshFinish(PullToRefreshLayout.FAIL);
              }

              @Override
              public void onCancelled(CancelledException cex) {

              }

              @Override
              public void onFinished() {

              }
          });

    }
    public void append(final int pagenow, final int userId, final String userCity,
                       final String userArea, final String userLongitude, final String userLatitude, final String userAddress, final String userFriendscircleType){
       lastloading=true;
        Map<String,String> map = new HashMap();
        map.put("pagenow", pagenow + "");
        map.put("userId", userId + "");
        map.put("userCity", "" + userCity);
        map.put("userArea", "" + userArea);
        map.put("userLongitude", "" + userLongitude);
        map.put("userLatitude", "" + userLatitude);
        map.put("userAddress", "" + userAddress);
        map.put("userFriendscircleType", "" + userFriendscircleType);
        Xutils.POST(HttpUrl.usefriendcircleBylocation, map, new CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                lastloading=false;
                Gson gson=new Gson();
                FriendCircleDomain domain=gson.fromJson(result,FriendCircleDomain.class);

                if (domain.getData() != null && domain.getData().size() != 0) {
                    if (adpter == null) {
                        recyclerview.setAdapter(adpter = new RecylcerAdaper(mActivity,domain.getData()));
                        recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
                            @Override
                            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                super.onScrollStateChanged(recyclerView, newState);
                                if (currentlastitem == lm.getItemCount() - 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                                    if (YanchuFragment_Saishi.this.pagenow == 1 && adpter.dataBeen.size() >= 10 && lastloading == false) {
                                        YanchuFragment_Saishi.this.pagenow++;
                                        append(pagenow,userId,userCity,userArea,userLongitude,
                                                userLatitude,userAddress,userFriendscircleType);
                                    }
                                }
                            }

                            @Override
                            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                super.onScrolled(recyclerView, dx, dy);
                                currentlastitem = lm.findLastVisibleItemPosition();
                            }
                        });
                    } else {
                        adpter.initAppend(domain.getData());
                    }

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                lastloading=false;
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

}
